import { getwxAppletUser, getFRSSOToken, getAppletUser } from '@/common/utils/api.js'
export async function judgeApp() {
    /**
     * author hezhilong 
     * time 2022-08-22
     * 1.先判断是不是浙里办环境
     * 2,如果是浙里办环境继续判断三端如果不是继续走本地开发逻辑便于打包后网页版使用
     * 3.process.env.NODE_ENV == 'production' 发布环境 process.env.NODE_ENV == 'develop' 生产环境
     * 4.获取适老化版本
     */
    ZWJSBridge.getUiStyle().then(res => {
        switch (res.uiStyle) {
            case 'elder':
                console.log(res.uiStyle)
                uni.setStorageSync('uiStyle', res.uiStyle)
                break;
            default:
                console.log(res.uiStyle)
                uni.setStorageSync('uiStyle', 'normal')
        }
    });
    const sUserAgent = window.navigator.userAgent.toLowerCase()
    // 浙里办APP
    const bIsDtDreamApp = sUserAgent.indexOf('dtdreamweb') > -1
    // 浙里办支付宝小程序
    const bIsAlipayMini = sUserAgent.indexOf('miniprogram') > -1 && sUserAgent.indexOf('alipay') > -1 //废弃 现在微信小程序和支付宝小程序用一套
    //微信端
    ZWJSBridge.onReady(async() => {
        console.log(ZWJSBridge.ssoTicket, '=================')
        if (ZWJSBridge.ssoTicket) {
            const res = await ZWJSBridge.ssoTicket({})
            console.log(res, '==========================')
            console.log(res.result === true)
            //判断是否为微信小程序以及支付宝小程序
            if (res && res.result === true) {
                if (res.ticketId) {
                    console.log(res.ticketId)
                    // TODO 应用方服务端微信单点登录接口
                    // me.ssoLogin()
                    const res6 = await getwxAppletUser(res.ticketId)
                    if (res6.data.hasUserSystem) {
                        uni.setStorageSync('token', res6.data.token)
                        //存当前登录人的信息
                    } else {
                        //需要注册人员信息
                        //先跳转注册页面
                        uni.navigateTo({
                            url: '/pages/user/register'
                        })
                    }
                    //存当前登录人的信息
                    uni.setStorageSync('userData', res6.data.zLBUserInfo)
                    uni.setStorageSync('userId', res6.data.userId)
                    uni.setStorageSync('ISWechat', '1')
                    console.log(res6.data, '===========================weixin')
                    setPoints(res6.data.zLBUserInfo)
                    //写微信的登录方法
                } else {
                    //当“浙里办”单点登录失败或登录态失效时调用 ZWJSBridge.openLink 方法重
                    //新获取 ticketId。
                    ZWJSBridge.openLink({ type: 'reload' }).then((res) => {
                        res.ticketId
                    })
                }
            } else {
                //非微信端
                uni.setStorageSync('ISWechat', '0')
                let servicecode = '17ce0a9ca3034da28dda1cb381ab3d39'//需要替换成现在项目的sericecode
                let gotoPath = 'https://mapi.zjzwfw.gov.cn/web/mgop/gov-open/zj/2002266277/reserved/index.html'
                let gotoPath1 = 'https://mapi.zjzwfw.gov.cn/web/mgop/gov-open/zj/2002266277/lastTest/index.html'
                let loginPathBy1 = '' //个人用户 单点登录网址
                loginPathBy1 = `https://puser.zjzwfw.gov.cn/sso/mobile.do?action=oauth&scope=1&servicecode=${servicecode}&redirectUrl=`
                let herfBy1 = loginPathBy1 + encodeURIComponent(gotoPath)
                let ticket = getUrlParam('ticket') || ''//个人 
                let ssotoken = getUrlParam('ssotoken') || '' //法人
                let ssoticket = getUrlParam('ssoticket') || ''//法人
                let spappurl = 'https://nfzjszlb.jst.zj.gov.cn/eca/fwjd/dataexchangeserver/zlbsso/redirectFaRenSpAppUrl'//需要替换
                let loginPathBy2 = 'https://esso.zjzwfw.gov.cn/opensso/spsaehandler/metaAlias/sp?spappurl='
                let herfBy2 = loginPathBy2 + spappurl
                ZWJSBridge.onReady(async () => {
                    ZWJSBridge.getUserType({})
                        .then(async (result) => {
                            const { userType } = result
                            uni.setStorageSync('isPer', userType)
                            if (userType == 0 || userType == 1) {
                                //个人
                                if (!ticket && bIsDtDreamApp) {
                                    window.location.href = herfBy1
                                    console.log(window.location.href, '------------------------------------------------window.location.href1')
                                } else {
                                    //写个人登录方法
                                    const res = await getAppletUser(ticket)
                                    console.log(res,'===============================')
                                    if (res.data.hasUserSystem) {
                                        uni.setStorageSync('token', res.data.token)
                                    } else {
                                        //需要注册人员信息
                                        //先跳转注册页面
                                        uni.navigateTo({
                                            url: '/pages/user/register'
                                        })
                                    }
                                    uni.setStorageSync('userData', res.data.zLBUserInfo)
                                    uni.setStorageSync('userId', res.data.userId)
                                    setPoints(res.data.zLBUserInfo)
                                    // uni.navigateTo({
                                    //     url: '/'
                                    // })
                                }
                            } else if (userType == 2) {
                                if (!ssoticket) {
                                    window.location.href = herfBy2
                                } else {
                                    //写法人登录方法
                                    const res1 = await getFRSSOToken(ssotoken, ssoticket)
                                    if (res1.data.hasUserSystem) {
                                        uni.setStorageSync('token', res1.data.token)
                                    } else {
                                        //需要注册人员信息
                                        //先跳转注册页面
                                        console.log('3333333333333333')
                                        uni.navigateTo({
                                            url: '/'
                                        })
                                    }
                                    if (uni.getStorageSync('token')) {
                                        uni.navigateTo({
                                            url: '/'
                                        })
                                    }
                                    uni.setStorageSync('userData', res1.data.zLBUserInfo)
                                    setPoints(res1.data.zLBUserInfo)
                                }
                            }
                        })
                        .catch((error) => {
                            console.log(error)
                        })
                })
            }
        } else {
            alert('12')
        }
    })
}
function getUrlParam(name) {
    VConsole
    var results = new RegExp('[?&]' + name + '=([^&#]*)').exec(window.location.href)
    if (results == null) {
        return null
    }
    return decodeURI(results[1]) || 0
}

function setPoints(data, data1) {
    const zwlog = new ZwLog({
        _user_id: data.userid,
        _user_nick: data.username,
    })
    zwlog.onReady(function () {
        zwlog.sendPV({
            miniAppId: '2001905684',
            Page_duration: '10s',
            t2: '1.2s',
            t0: '0.2s',
            miniAppName: '农房浙建事',
            log_status: window.localStorage.getItem('token') ? '02' : '01',
        })
        zwlog.record('yourTrackerEventCode', 'CLK', { Test1: '测试参数 1' })
        let { metaInfo } = zwlog
    })
}